package com.duyutian.controller.hiwodytController;

import com.duyutian.common.CusAccessObjectUtil;
import com.duyutian.common.ServiceResult;
import com.duyutian.domain.Loger;
import com.duyutian.model.Article;
import com.duyutian.util.RedisTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * Created by dyt on 2018/10/20.
 */
/*文章操作类*/
@Controller
@RequestMapping("/hiwodyt")
public class HiwodytArticleController {
    @Autowired
    private RedisTools redisTools;

    //文章点赞
    @RequestMapping("/voteUp")
    @ResponseBody
    public ServiceResult voteUp(HttpServletRequest request, String articleId) {
        //判断该用户是否已经给该文章进行点赞
        //获取用户ip
        String ipAddress = CusAccessObjectUtil.getIpAddress(request);
        ArrayList<Loger> logs = redisTools.getLogs();
        for (Loger l :
                logs) {
            if (l.getVotelist().contains(Long.parseLong(articleId))) {
                return ServiceResult.error(101, "您已经点赞过此文章");
            }
        }


        //文章点赞
        Article byId = Article.dao.findById(Long.parseLong(articleId));
        byId.setVoteUp(byId.getVoteUp() + 1);
        byId.update();
        //记录访客点赞记录

        for (Loger l :
                logs) {
            if (l.getIp().equals(ipAddress)) {
                l.getVotelist().add(Long.parseLong(articleId));
            }
        }
        redisTools.serLogs(logs);
        return ServiceResult.success(byId.getVoteUp());
    }


}
